package cc.eddic.practice.concurrency.impl;
import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogItemParser;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogItemParserImpl implements LogItemParser {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);

    @Override
    public Optional<LogItem> parse(String logLine) {
        Pattern pattern =  Pattern.compile("(?<ip>\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+[\\w\\-]+\\s+[\\w\\-]+\\s+\\[(?<dt>\\d+/\\w+/\\d+:\\d+:\\d+:\\d+\\s+\\+\\d+)]\\s+\"(?<request>.*)\"\\s+(?<status>\\d+)\\s+(?<sent>\\d+)\\s+\"(?<referer>[^\"]+)\"\\s+\"(?<ua>[^\"]+)\"");
        Matcher matcher = pattern.matcher(logLine);
        if (matcher.find()) {
            String ip = matcher.group("ip");
            LocalDateTime time = LocalDateTime.parse(matcher.group("dt"), DATE_TIME_FORMATTER);
            String[] requestDetails = extractRequestDetails(matcher.group("request"));
            String request = matcher.group("request");
            String method = requestDetails[0];
            String path = requestDetails[1];
            String protocol = requestDetails[2];

            int status = Integer.parseInt(matcher.group("status"));
            long bytes = Long.parseLong(matcher.group("sent"));
            String referer = matcher.group("referer");
            String userAgent = matcher.group("ua");

            return Optional.of(new LogItem(ip, time, request, method, path, null, protocol, status, bytes,referer,userAgent));
        }

        return Optional.empty();
    }

    private static final Pattern REQUEST_PATTERN = Pattern.compile("(?<method>\\w+)\\s+(?<url>[^ ]+)\\s+(?<protocol>[^ ]+)");

    public static String[] extractRequestDetails(String request) {
        Matcher matcher = REQUEST_PATTERN.matcher(request);

        if (matcher.matches()) {
            String method = matcher.group("method");
            String url = matcher.group("url");
            String protocol = matcher.group("protocol");

            String path = url.split("\\?")[0];

            return new String[]{method, path, protocol};
        }
        return new String[]{null, null, null};
    }

//    private String[] extractRequestDetails(String request) {
//        String[] requestDetails = request.split("\\s+", 3);
//
//        if (requestDetails.length == 3) {
//            String method = requestDetails[0];
//            String url = requestDetails[1];
//            String protocol = requestDetails[2];
//
//            String path = url.split("\\?")[0];
//
//            return new String[]{method, path, protocol};
//        }
//        return new String[]{null, null, null};
//    }

}